#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Pydantic 模型和数据验证示例
演示了如何使用 Pydantic 进行数据验证
"""

from fastapi import FastAPI
from pydantic import BaseModel, Field, validator
from typing import Union
from datetime import datetime

app = FastAPI()

# 基础模型
class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None

# 带约束的模型
class ItemWithConstraints(BaseModel):
    name: str = Field(..., min_length=1, max_length=50, description="商品名称")
    description: Union[str, None] = Field(None, max_length=300)
    price: float = Field(..., gt=0, description="价格必须大于0")
    tax: Union[float, None] = None

# 带验证器的模型
class User(BaseModel):
    id: int
    name: str = "John Doe"
    signup_ts: Union[datetime, None] = None
    friends: list[int] = []
    
    @validator('name')
    def name_must_not_be_empty(cls, v):
        if not v.strip():
            raise ValueError('名称不能为空')
        return v.title()

@app.post("/items/")
async def create_item(item: Item):
    return item

@app.post("/items-with-constraints/")
async def create_item_with_constraints(item: ItemWithConstraints):
    return item

@app.post("/users/")
async def create_user(user: User):
    return user

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8004, log_level="info")